package cn.zebra.dev.admin.module.discounts.controller;

import cn.zebra.dev.admin.module.discounts.dto.DiscountsShopListDTO;
import cn.zebra.dev.admin.module.discounts.dto.ProductItemDTO;
import cn.zebra.dev.admin.module.discounts.dto.ShopItemDTO;
import cn.zebra.dev.admin.module.discounts.vo.DiscountsShopListVO;
import cn.zebra.dev.admin.module.login.SecurityAdminService;
import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.other.module.discountsShop.entity.DiscountsShopEntity;
import cn.zebra.dev.other.module.discountsShop.service.DiscountsShopService;
import cn.zebra.dev.other.module.shopAdmin.entity.ShopAdminEntity;
import cn.zebra.dev.other.module.shopAdmin.service.ShopAdminService;
import cn.zebra.dev.product.module.product.entity.ProductEntity;
import cn.zebra.dev.product.module.product.service.ProductService;
import cn.zebra.dev.shop.module.shop.entity.ShopEntity;
import cn.zebra.dev.shop.module.shop.service.ShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wzhsun.cn
 * @version 1.0
 * @date 2020/5/8
 */

@RestController
@Api(tags = "店铺优惠券模块")
@RequestMapping("/discountShop")
public class DiscountsShopController {

    @Autowired
    private DiscountsShopService discountsShopService;

    @Autowired
    private SecurityAdminService adminService;

    @Autowired
    private ShopAdminService shopAdminService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ShopService shopService;

    @GetMapping("/list")
    @ApiOperation("店铺优惠券列表")
    public Result<PageUtils<DiscountsShopListDTO>> list(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page) {
        Map<String, Object> map = new HashMap<>();
        map.put("limit", limit);
        map.put("page", page);
        ShopAdminEntity shopAdminEntity = shopAdminService.findShopIdByUserId(adminService.getId());
        if (shopAdminEntity == null) {
            return Result.error("您还未拥有自己的店铺，快去申请吧！");
        }
        map.put("shopId", shopAdminEntity.getShopId());
        ProductEntity productEntityo = productService.findProductIdByShopId(shopAdminEntity.getShopId());
        if (productEntityo == null) {
            productEntityo.setId(0L);
        }
        map.put("productId", productEntityo.getId());
        PageUtils<DiscountsShopEntity> pageUtils = discountsShopService.findPage(map);
        PageUtils<DiscountsShopListDTO> data = new PageUtils<>(pageUtils);
        List<DiscountsShopEntity> list = pageUtils.getList();
        List<DiscountsShopListDTO> dtoList = new LinkedList<>();
        if (list.size() > 0) {
            List<Long> discountsShopIds = list.stream().map(DiscountsShopEntity::getShopId).collect(Collectors.toList());
            List<Long> discountsProductIds = list.stream().map(DiscountsShopEntity::getProductId).collect(Collectors.toList());
            List<ShopEntity>  shopEntities = shopService.findByIds(discountsShopIds);
            List<ProductEntity>  productEntities = productService.findByIds(discountsProductIds);
            list.forEach(entity -> {
                DiscountsShopListDTO dto = new DiscountsShopListDTO();
                BeanUtils.copyProperties(entity, dto);
                //判断优惠券状态0表示禁用 1 启用 2 过期
                LocalDateTime now = LocalDateTime.now();
                if (now.compareTo(dto.getStartTime()) > 0 && now.compareTo(dto.getEndTime()) < 0) {
                    dto.setDiscountsStatus(1);
                } else if (now.compareTo(dto.getEndTime()) > 0) {
                    dto.setDiscountsStatus(2);
                } else {
                    dto.setDiscountsStatus(0);
                }
                Optional<ShopEntity> shopEntityOptional = shopEntities.stream()
                        .filter(shopEntity -> shopEntity.getId().equals(entity.getShopId())).findAny();
                Optional<ProductEntity> productEntityOptional = productEntities.stream()
                        .filter(productEntity -> productEntity.getId().equals(entity.getProductId())).findAny();
                // 如果是店铺优惠券，那么返回优惠券的所属店铺信息
                if (shopEntityOptional.isPresent()){
                    ShopEntity shopEntity = shopEntityOptional.get();

                    if (dto.getDiscountsType() == 1) {
                        ShopItemDTO shopItemDTO = new ShopItemDTO();
                        BeanUtils.copyProperties(shopEntity, shopItemDTO);
                        dto.setShopItemDTOS(shopItemDTO);
                        if (dto.getProductId() != 0 && productEntityOptional.isPresent()) {
                            ProductEntity product = productEntityOptional.get();
                            ProductItemDTO productItemDTO = new ProductItemDTO();
                            BeanUtils.copyProperties(product, productItemDTO);
                            dto.setProductItemDTOS(productItemDTO);
                        }
                    }
                    // 如果是商品优惠券，那么返回优惠券的所属商品信息
                    if (dto.getDiscountsType() == 2 && productEntityOptional.isPresent()) {
                        ProductEntity product = productEntityOptional.get();
                        ProductItemDTO productItemDTO = new ProductItemDTO();
                        BeanUtils.copyProperties(product, productItemDTO);
                        dto.setProductItemDTOS(productItemDTO);
                    }
                }
                dtoList.add(dto);
            });
        }
        data.setList(dtoList);
        return Result.success(data);
    }


    @GetMapping("/get/{id}")
    @ApiOperation("店铺优惠券详情")
    public Result<DiscountsShopListDTO> get(@PathVariable Long id) {
        DiscountsShopEntity discountsShopEntity = discountsShopService.findById(id);
        if (discountsShopEntity == null) {
            return Result.error("没有此优惠券");
        }
        DiscountsShopListDTO discountsShopListDTO = new DiscountsShopListDTO();
        BeanUtils.copyProperties(discountsShopEntity, discountsShopListDTO);
        return Result.success(discountsShopListDTO);
    }

    @PostMapping("/save")
    @ApiOperation("店铺新增优惠券")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@Valid @RequestBody DiscountsShopListVO vo) {
        DiscountsShopEntity discountsEntity = new DiscountsShopEntity();
        LocalDateTime createTime = LocalDateTime.now();
        discountsEntity.setCreateTime(createTime);
        if (vo.getProductId() == 0) {
            //设置优惠券类型为店铺类型
            discountsEntity.setDiscountsType(1);
        } else {
            discountsEntity.setDiscountsType(2);
        }
        discountsEntity.setProductId(vo.getProductId());
        discountsEntity.setDiscountsId(String.valueOf(System.currentTimeMillis()));
        discountsEntity.setAmount(vo.getAmount());
        ShopAdminEntity shopAdminEntity = shopAdminService.findShopIdByUserId(adminService.getId());
        if (shopAdminEntity == null) {
            return Result.error("您还未拥有自己的店铺，快去申请吧！");
        }
        discountsEntity.setShopId(shopAdminEntity.getShopId());
        discountsEntity.setDescribes(vo.getDescribes());
        discountsEntity.setDiscountsNumb(vo.getDiscountsNumb());
        //优惠卷条件
        discountsEntity.setConditionType(vo.getConditionType());
        if (vo.getConditionType() == 0) {
            discountsEntity.setConditions(0L);
        } else {
            discountsEntity.setConditions(vo.getConditions());
        }
        //判断优惠券过期时间
        int isExpired = vo.getStartTime().compareTo(vo.getEndTime());
        if (isExpired > 0) {
            return Result.error("过期时间不能小于起始时间!!");
        }
        discountsEntity.setStartTime(vo.getStartTime());
        discountsEntity.setEndTime(vo.getEndTime());
        discountsEntity.setDeleteFlag(false);
        //判断优惠券状态0表示禁用 1 启用 2 过期
        if (createTime.compareTo(vo.getStartTime()) > 0 && createTime.compareTo(vo.getEndTime()) < 0) {
            discountsEntity.setDiscountsStatus(1);
        } else if (createTime.compareTo(vo.getEndTime()) > 0) {
            discountsEntity.setDiscountsStatus(2);
        } else {
            discountsEntity.setDiscountsStatus(0);
        }
        discountsEntity.setDiscountsImg(vo.getDiscountsImg());
        if (!discountsShopService.save(discountsEntity)) {
            return Result.error("添加失败");
        }
        return Result.success("添加成功");
    }


    @PostMapping("/update/{id}")
    @ApiOperation("店铺修改优惠券")
    @Transactional(rollbackFor = Exception.class)
    public Result update(@PathVariable Long id, @Valid @RequestBody DiscountsShopListVO vo) {
        DiscountsShopEntity discountsShopEntity = discountsShopService.findById(id);
        BeanUtils.copyProperties(vo, discountsShopEntity);
        discountsShopEntity.setDeleteFlag(false);
        if (vo.getProductId() == 0) {
            //设置优惠券类型为店铺类型
            discountsShopEntity.setDiscountsType(1);
        } else {
            discountsShopEntity.setDiscountsType(2);
        }
        if (vo.getConditionType() == 0) {
            discountsShopEntity.setConditions(0L);
        } else {
            discountsShopEntity.setConditions(vo.getConditions());
        }
        //判断优惠券过期时间
        int isExpired = vo.getStartTime().compareTo(vo.getEndTime());
        if (isExpired > 0) {
            return Result.error("过期时间不能小于起始时间!!");
        }
        //判断优惠券状态0表示禁用 1 启用 2 过期
        LocalDateTime now = LocalDateTime.now();
        if (now.compareTo(discountsShopEntity.getStartTime()) > 0 && now.compareTo(discountsShopEntity.getEndTime()) < 0) {
            discountsShopEntity.setDiscountsStatus(1);
        } else if (now.compareTo(discountsShopEntity.getEndTime()) > 0) {
            discountsShopEntity.setDiscountsStatus(2);
        } else {
            discountsShopEntity.setDiscountsStatus(0);
        }
        if (!discountsShopService.updateDiscountsById(id, discountsShopEntity)) {
            return Result.error("修改失败");
        }
        return Result.success("修改成功");
    }


    @GetMapping("/delete/{id}")
    @ApiOperation("店铺删除优惠券")
    public Result delete(@PathVariable Long id) {
        DiscountsShopEntity entity = discountsShopService.findById(id);
        entity.setDeleteFlag(true);
        if (discountsShopService.update(entity, "id = {0}", id)) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败!");
    }

}
